<template>
  <basic-container>
    <div class="app-container">
      <el-row :gutter="40">
        <!-- <el-col :span="4">
          <el-input v-model="filterText" clearable size="small" placeholder="输入名称进行过滤" />          
          <div ref="filterTreeWrapper" class="filter-tree-wrapper">
            <el-tree
              v-loading="listCatetory"
              ref="tree2"
              :data="data2"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              highlight-current
              class="filter-tree"
              default-expand-all
              @current-change="onClickNode"
            />
          </div>
        </el-col> -->
        <el-col :span="24">
          <div class="filter-container" v-if="themeId==0">
            <el-button
              v-waves
              class="filter-item"
              size="small"
              type="primary"
              icon="el-icon-plus"
              @click="addRow"
            >添加</el-button>
            <el-input
              v-model="listQuery.title"
              size="small"
              clearable
              placeholder="商品名称"
              style="width: 220px;"
              class="filter-item"
              @keyup.enter.native="getList"
            />
            <el-select
              v-model="listQuery.status"
              size="small"
              placeholder="上线状态"
              class="filter-item"
              clearable
            >
              <el-option
                v-for="(opt) in $constants.goodsStatusOptions"
                :key="opt.value"
                :label="opt.title"
                :value="opt.value"
              />
            </el-select>
            <el-select
              v-model="listQuery.checkStatus"
              size="small"
              placeholder="审核状态"
              class="filter-item"
              clearable
            >
              <el-option
                v-for="(title,value) in checkStatusOptions"
                :key="value"
                :label="title"
                :value="value"
              />
            </el-select>
            <!-- <el-select v-model="listQuery.supplierId" filterable clearable size="small" placeholder="供应商" v-if="!selectable && goodsType==1">
              <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.supplierName">{{item.supplierName}}</el-option>
            </el-select> -->
            &nbsp;
            &nbsp;
            <el-button
              v-waves
              class="filter-item"
              type="primary"
              size="small"
              icon="el-icon-refresh"
              @click="getList"
            >搜索</el-button>
            <br>
            <br>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="danger"
              v-perm="'/admin/goods/modify_online_status'"
              v-if="!selectable"
              icon="el-icon-edit"
              @click="handleBatchOffline"
            >批量下线</el-button>
            <el-button
              v-waves
              size="small"
              v-perm="'/admin/goods/modify_online_status'"
              class="filter-item"
              v-if="!selectable"
              type="primary"
              icon="el-icon-edit"
              @click="handleBatchOnline"
            >批量上线</el-button>
            
            <el-button
              v-waves
              size="small"
              class="filter-item"
              v-if="!selectable"
              type="primary"
              v-perm="'/admin/goods/check'"
              icon="el-icon-edit"
              @click="handleBatchResolve"
            >批量审核通过</el-button>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="danger"
              v-perm="'/admin/goods/check'"
              v-if="!selectable"
              icon="el-icon-edit"
              @click="handleBatchReject"
            >批量审核拒绝</el-button>
            
            <!-- <el-button
              v-waves
              size="small"
              class="filter-item"
              v-perm="'/admin/goods/set_public_show'"
              type="primary"
              v-if="!selectable"
              icon="el-icon-edit"
              @click="handleBatchSetPublishShow(1)"
            >批量主商城可见</el-button>
            <el-button
              v-waves
              size="small"
              v-perm="'/admin/goods/set_public_show'"
              class="filter-item"
              type="danger"
              v-if="!selectable"
              icon="el-icon-edit"
              @click="handleBatchSetPublishShow(0)"
            >批量主商城不可见</el-button> -->
          </div>
          <div class="filter-container" v-else style="display:flex;flex-direction:row;align-items:flex-start;">
            <el-button
              v-waves
              class="filter-item"
              type="primary"
              size="small"
              icon="el-icon-refresh"
              @click="getList"
            >刷新</el-button>
            <div v-if="!selectable && notRelation==false" style="margin-right:20px;">
              <el-input placeholder="请输入内容" v-model="listQuery.title" clearable size="mini" class="input-with-select">
                <el-button slot="append" @click="getList" size="mini" icon="el-icon-search"></el-button>
              </el-input>
            </div>

            <div style="flex:1;display:flex;flex-direction:row;align-items:flex-start;" v-if="notRelation">
              <div style="color:#999;padding-right:10px;padding-top:5px;">
                已选{{selectedThemeGoods.length}}件商品
              </div>
              <div>
                <el-input placeholder="请输入内容" v-model="listQuery.title" clearable size="mini" class="input-with-select">
                  <el-button slot="append" @click="getList" size="mini" icon="el-icon-search"></el-button>
                </el-input>
              </div>
              <div style="flex:1">
                <el-tag closable @close="handleRemoveThemeGoods(itemIndex,item)" class="selected-theme-goods" v-for="(item,itemIndex) in selectedThemeGoods" :key="itemIndex">
                  {{item.title}}
                </el-tag>
              </div>
              
              <el-button
              v-waves
              size="small"
              class="filter-item"
              type="primary"
              @click="handleSelectSelectedGoods"
            >确认选择</el-button>
            </div>
             <el-button
              v-waves
              size="small"
              class="filter-item"
              type="danger"
              v-if="!selectable && notRelation==false"
              icon="el-icon-edit"
              @click="handleBatchRemoveGoods"
            >移出所选商品</el-button>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="primary"
              v-if="!selectable && notRelation==false"
              icon="el-icon-edit"
              @click="handleShowAddGoodsDialog"
            >添加商品</el-button>
            
          </div>
          <el-table
            v-loading="listLoading"
            :data="list"
            :height="tableHeight"
            border
            fit
            @selection-change="handleSelectionChange"
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column type="selection" width="55" align="center" v-if="notRelation==false"></el-table-column>
            <!-- 
            <el-table-column label="主播手机号" width="120px" align="center" v-if="goodsType==2">
              <template slot-scope="scope">{{ scope.row.userMobile }}</template>
            </el-table-column>
            <el-table-column label="主播姓名" width="100px" align="center" v-if="goodsType==2">
              <template slot-scope="scope">{{ scope.row.realName }}</template>
            </el-table-column> -->
             <el-table-column label="商品ID" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column label="商品标题" width="200px" align="center">
              <template slot-scope="scope">{{ scope.row.title }}</template>
            </el-table-column>
            <el-table-column label="商品副标题" width="200px" align="center">
              <template slot-scope="scope">{{ scope.row.subTitle||"" }}</template>
            </el-table-column>
            
            <!-- <el-table-column label="商品类型" width="120px" align="center">
              <template slot-scope="scope">{{ scope.row.goodsType |goodsTypeFilter }}</template>
            </el-table-column> -->
            <el-table-column label="商品分类" width="120px" align="center">
              <template slot-scope="scope">{{ scope.row.categoryName }}</template>
            </el-table-column>
            <!-- <el-table-column label="供应商" width="120px" align="center" v-if="goodsType==1">
              <template slot-scope="scope">{{ scope.row.supplierName }}</template>
            </el-table-column> -->
            <el-table-column label="商品主图" width="130px" align="center">
              <template slot-scope="scope">
                <img :src="scope.row.mainImg|imgUrl" alt style="height:60px;" />
              </template>
            </el-table-column>
             <el-table-column label="状态" width="100px" align="center">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status | statusColorFilter"
                >{{ scope.row.status | statusFilter }}</el-tag>
              </template>
            </el-table-column>
             <!-- <el-table-column label="主商城可见" width="100px" align="center" v-if="goodsType==2">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.publicShowFlag | statusColorFilter"
                >{{ scope.row.publicShowFlag | publicShowFlagFilter }}</el-tag>
              </template>
            </el-table-column> -->
            <el-table-column label="审核状态" width="100px" align="center">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.checkStatus | checkStatusColorFilter"
                >{{ scope.row.checkStatus | checkStatusFilter }}</el-tag>
              </template>
            </el-table-column>
              <el-table-column label="审核备注" width="160px" align="center">
              <template slot-scope="scope">{{ scope.row.checkRemark }}</template>
            </el-table-column>
            <el-table-column label="审核人" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.checkOperator }}</template>
            </el-table-column>
            <el-table-column label="商品销售价" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.salePrice }}</template>
            </el-table-column>

            <el-table-column label="商品市场价" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.marketPrice }}</template>
            </el-table-column>
            
            <el-table-column label="商品库存" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.stockNum }}</template>
            </el-table-column>

            <el-table-column label="商品销量" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.saleNum }}</template>
            </el-table-column>
            <el-table-column label="排序" width="100px" align="center">
              <template slot-scope="scope">{{ scope.row.sortNum }}</template>
            </el-table-column>
           
            <el-table-column label="创建时间" width="180px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="修改时间" width="180px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.modifyTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              min-width="260"
              v-if="!selectable && themeId == 0"
              class-name="small-padding"
            >
              <template slot-scope="scope">
                <div style="line-height:2.4;">
                <el-button type="primary" size="mini" @click="editRow(scope.row)">修改</el-button>
                <!-- <el-button type="warning" size="mini" @click="handleEditStock(scope.row)">修改库存</el-button> -->
                <el-button
                  type="primary"
                  @click.stop="handleResolve(scope.row)"
                  size="mini"
                  v-if="scope.row.checkStatus != 10"
                  v-perm="'/admin/goods/check'"
                >审核通过</el-button>
                <el-button
                  type="danger"
                  @click.stop="handleReject(scope.row)"
                  size="mini"
                  v-if="scope.row.checkStatus != 5"
                  v-perm="'/admin/goods/check'"
                >审核拒绝</el-button>
                <template v-if="goodsType==2">
                  <el-button
                  v-if="scope.row.publicShowFlag!=1"
                  v-perm="'/admin/goods/set_public_show'"
                  type="success"
                  size="mini"
                  @click="handleSetPublishShow(scope.row,1)"
                >主商城可见</el-button>
                <el-button v-else 
                v-perm="'/admin/goods/set_public_show'"
                type="danger" size="mini" @click="handleSetPublishShow(scope.row,0)">主商城不可见</el-button>
                </template>
                
                <br/>
                <el-button
                  v-if="scope.row.status!=1"
                  v-perm="'/admin/goods/modify_online_status'"
                  type="success"
                  size="mini"
                  @click="handleSetOnline(scope.row)"
                >上线</el-button>
                <el-button v-else 
                v-perm="'/admin/goods/modify_online_status'"
                type="default" size="mini" @click="handleSetOffline(scope.row)">下线</el-button>
                
                <el-button 
                v-perm="'/admin/goods/delete'"
                size="mini" type="danger" @click="deleteRow(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              min-width="160"
              v-else-if="selectable"
              class-name="small-padding"
            >
            <template slot-scope="scope">
              <el-button
                  type="primary"
                  @click.stop="handleSelectGoods(scope.row)"
                  icon="el-icon-edit"
                  size="mini"
                >选择</el-button>
            </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              min-width="160"
              v-else-if="notRelation==false"
              class-name="small-padding"
            >
            <template slot-scope="scope">
             <el-button 
                size="mini" type="danger" @click="handleRemoveRow(scope.row)">移出</el-button>
            </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              min-width="160"
              v-else
              class-name="small-padding"
            >
            <template slot-scope="scope">
             <el-button size="mini" v-if="!scope.row.selected" type="primary" @click="handleSelectThemeGoods(scope.row)">选择</el-button>
             <el-button size="mini" v-else type="info" @click="handleSelectThemeGoods(scope.row)">取消选择</el-button>
            </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              :current-page.sync="listQuery.pageNo"
              :page-sizes="[10,20,30, 50]"
              :page-size="listQuery.pageSize"
              :total="total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

          <el-dialog
            :close-on-click-modal="false"
            :close-on-press-escape="false"  
            :append-to-body="true"
            :title="isEditing?'修改':'添加'"
            :visible.sync="dialogFormVisible"
            width="1200px"
          >
            <el-form
              ref="dataForm"
              v-loading="isLoadingDetail"
              :rules="rules"
              :model="temp"
              label-position="left"
              label-width="120px"
              style="margin-left:20px;margin-right:20px;"
            > 
              <div class="title">1、商品基本信息</div>
              <el-row>
                <el-col :span="8">
                  <!-- <el-form-item label="商品分类" prop="categoryId">
                    <el-select v-model="temp.categoryId" filterable>
                        <el-option v-for="item in categoryOptions" :key="item.id" :value="item.id" :label="item.categoryName">{{item.categoryName}}</el-option>
                    </el-select>
                  </el-form-item> -->
                  <el-form-item label="营销所属分类" prop="categoryId">
                    <category-cascader ref="categoryRef" :type='2' placeholder="营销所属分类" v-model="temp.categoryId" :changeOnSelect="false"></category-cascader>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="16" v-if="goodsType==1">
                  <el-form-item label="供应商" prop="supplierId">
                    <el-select v-model="temp.supplierId" filterable>
                        <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.supplierName">{{item.supplierName}}</el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
              </el-row>
              <el-form-item label="商品标题" prop="title">
                  <el-input v-model="temp.title" placeholder="请输入商品标题" />
              </el-form-item>
               <el-form-item label="商品副标题" prop="subTitle">
                  <el-input v-model="temp.subTitle" placeholder="请输入商品副标题" />
              </el-form-item>
              <el-row>
                  <el-col :span="8">
                  <el-form-item label="市场价格" prop="marketPrice">
                    <el-input-number v-model="temp.marketPrice" :precision="2" placeholder="请输入市场价格" />
                  </el-form-item>
                </el-col>
                  <!-- <el-col :span="8">
                  <el-form-item label="推广佣金比例" prop="agentCommRate">
                    <el-input-number v-model="temp.agentCommRate" :precision="2" placeholder="请输入推广佣金比例" />
                    %
                  </el-form-item>
                </el-col> -->
                  <!-- <el-col :span="8">
                  <el-form-item label="平台佣金比例" prop="platCommRate">
                    <el-input-number v-model="temp.platCommRate" :precision="2" placeholder="请输入平台佣金比例" />
                    %
                  </el-form-item>
                </el-col> -->
                
                <!-- <el-col :span="8">
                  <el-form-item label="运费模板" prop="expressTemplateId">
                    <el-select v-model="temp.expressTemplateId" placeholder="请选择运费模板" clearable>
                      <el-option
                        v-for="(item,itemIndex) in expressTemplates"
                        :key="itemIndex"
                        :label="item.templateName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <!-- <el-col :span="8" >
                  <el-form-item label="退货地址" prop="returnAddressId">
                    <el-select
                      v-model="temp.returnAddressId"
                      placeholder="请选择退货地址"
                      clearable
                    >
                      <el-option
                        v-for="(item,itemIndex) in returnAddressList"
                        :key="itemIndex"
                        :label="item.receiverAddress"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col> -->
                 <el-col :span="8">
                  <el-form-item label="排序" prop="sortNum">
                    <el-input-number v-model="temp.sortNum" placeholder="排序" />
                  </el-form-item>
                </el-col>
              </el-row>
               <el-form-item label="商品轮播图" prop="goodsImg">
                  <xd-upload v-model="temp.goodsImg" :limit="9"/>
              </el-form-item>
              <!-- <el-form-item label="商品描述" prop="profile">
                  <el-input v-model="temp.profile" :rows="5" type="textarea" placeholder="商品描述(最多500字)" maxlength="500"></el-input>
              </el-form-item> -->
              <el-form-item label="商品详情图" prop="goodsDescImg">
                  <xd-upload v-model="temp.goodsDescImg" :firstAsCover="false" :limit="20" />
              </el-form-item>
              <div class="title">2、商品规格与库存</div>
              <div style="padding-bottom:30px;">
                <goods-sale-prop ref="goodsRule" v-model="temp.skuList"></goods-sale-prop>
              </div>
              <!-- <div class="title">3、服务与承诺</div>
              <el-row>
                <el-col :span="4">
                  <el-form-item label="可退款" prop="refundable">
                    <el-switch v-model="temp.refundable" :active-value="1" :inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="7天可退款" prop="serven_refundable">
                    <el-switch
                      v-model="temp.serven_refundable"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="快速审核" prop="quick_authed">
                    <el-switch v-model="temp.quick_authed" :active-value="1" :inactive-value="0" />
                  </el-form-item>
                </el-col>
              </el-row> -->
            
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button :loading="isSubmiting" type="primary" @click="submitFormAction">确定</el-button>
            </div>
          </el-dialog>
        </el-col>
      </el-row>
      
      <el-dialog :visible.sync="addGoodsDialogShowedFlag" title="添加商品" width="1100px" v-if="!notRelation" append-to-body>
        <goods-index @onSelectThemeGoods="handleOnSelectThemeGoods" :themeId="themeId" :notRelation="true"></goods-index>
      </el-dialog>

    </div>
  </basic-container>
</template>

<script>
import { bannerPosTypes, goodsStatusOptions } from "../../constants/constants";
// import Tinymce from '@/components/Tinymce';
import goodsSaleProp from "@/components/goodsSaleProp.vue";
import categoryCascader from "@/components/categoryCascader.vue";
import * as apiCategoryObj from "@/api/goodsCategory";
import * as returnAddressApi from '@/api/returnAddress';
import * as apiGoodsObj from "@/api/goods";
import * as apiGoodsSelectedObj from '@/api/goodsSelected';
import * as apiGoodsThemeObj from '@/api/goodsTheme';
import * as supplierInfoObj from '@/api/supplierInfo';
import xdUploadVue from "@/components/sortableUpload.vue";
import goodsIndex from './index';
// 商品类型:1(平台商品)2(主播商品)
const goodsTypeOptions = ['平台商品','主播商品'];
// 审核状态:1(待审核)5(审核驳回)10(审核通过)
const checkStatusOptions = {1:'待审核',5:'审核驳回',10:'审核通过'};
const checkStatusColorOptions = {1:'danger',5:'info',10:'success'};
const publicShowFlagOptions = ['不可见','可见'];
export default {
  name:'goodsIndex',
  components: {
    "goods-sale-prop": goodsSaleProp,
     "xd-upload": xdUploadVue,
     'goodsIndex':goodsIndex,
     "category-cascader":categoryCascader
  },
  filters: {
    goodsTypeFilter(v){
      return goodsTypeOptions[v - 1];
    },
    checkStatusColorFilter(v){
      return checkStatusColorOptions[v];
    },
    checkStatusFilter(v){
      return checkStatusOptions[v];
    },
    publicShowFlagFilter(v){
      return publicShowFlagOptions[v];
    },
    statusFilter(value) {
      const b = goodsStatusOptions.filter(el => el.value === value)[0];
      if (b) {
        return b.title;
      }
      return ""; // #endregion
    },
    statusColorFilter(value) {
      if (value === 1) {
        return "primary";
      } else {
        return "danger";
      }
    }
  },
   
  props:{
    recomType:{
      type:Number,
      default:1
    },
    notRelation:{
      type:Boolean,
      default:false
    },
    goodsType:{
      type:Number,
      default:1
    },
    selectable:{
      type:Boolean,
      default:false
    },
    themeId:{
      type:Number,
      default:0
    }
  },
  data() {
    return {
      tableHeight: 0,
      checkStatusOptions,
      list: null,
      brandOptions: [],
      goodsTypeOptions,
      listCatetory: false,
      goodsStatusOptions,
      currentSelectedNode: null,
      defaultProps: {
        children: "children",
        label: "title",
        value: "id"
      },
      filterText: "",
      data2: [],
      isLoadingDetail:false,
      categoryOptions: [],
      isSubmiting: false,
      isEditing: false,
      bannerPosTypes,
      dialogFormVisible: false,
      pwdDialogFormVisible: false,
      listLoading: false,
      temp: {
        title: "",
        salePrice:0,
        marketPrice:0,
        platCommRate:0,
        agentCommRate:0,
        expressTemplateId:'',
        returnAddressId:'',
        categoryId:'',
        supplierId:'',
        skuList:[],
        goodsImg:[],
        goodsDescImg:[],
        goodsProps:''
      },
      total: 0,
      supplierList:[],
      rules: {
        goodsImg: [
          {
            required: true,
            message: "请上传至少一张商品轮播图",
            trigger: "change",
            type:"array"
          }
        ],
        sortNum: [
          {
            required: true,
            message: "请输入排序",
            trigger: "change"
          }
        ],
        title: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "change"
          }
        ],
        // agentCommRate: [
        //   {
        //     required: true,
        //     message: "请输入推广佣金比例",
        //     trigger: "change"
        //   }
        // ],
        platCommRate: [
          {
            required: true,
            message: "请输入平台佣金比例",
            trigger: "change"
          }
        ],
        goodsDescImg:[
          {
            required:false,
            message:'商品详情图不能超过20张',
            trigger:'change',
            max:20,
            type:'array'
          }
        ],
        categoryId: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "change",
            type: "number"
          }
        ],
        // supplierId: [
        //   {
        //     required: true,
        //     message: "请选择供应商",
        //     trigger: "change",
        //     type: "number"
        //   }
        // ],
        expressTemplateId: [
          {
            required: true,
            message: "请选择运费模板",
            trigger: "change",
            type: "number"
          }
        ],
        returnAddressId: [
          {
            required: true,
            message: "请选择退货地址",
            trigger: "change",
            type: "number"
          }
        ],
        marketPrice: [
          {
            required: true,           
            message: "请输入市场价格",
            trigger: "change"
          },{
            validator:(rule, value, callback)=>{
              if(value<=0) {
                callback(new Error('市场价必须大于0'));
              }
              callback();
            },
            trigger:'blur'
          }
        ]
      },
      listQuery: {
        title:"",
        pageNo: 1,
        pageSize: 10
      },
      selectedThemeGoods:[],
      addGoodsDialogShowedFlag:false,
      returnAddressList:[],
      expressTemplates: [],
      expressFreeConditions: []
    };
  },
  computed: {
    currentParentName() {
      if (this.currentSelectedNode) {
        return this.currentSelectedNode.title;
      }
      return "(无)";
    }
  },
  watch: {
  
    filterText(val) {
      this.$refs.tree2.filter(val);
    },
    themeId(){
      this.getList();
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 350;

    this.getList();
    if(this.goodsType >= 0) {
      this.listQuery.goodsType = this.goodsType;
    }
    this.loadExpressTemplates();
    this.loadAllNodes();
    // this.loadReturnAddressList();
    this.loadSupplierList();
    // this.$service.brand.listAll().then(data => {
    //   this.brandOptions = data;
    // });
  },
  // mounted() {
    // this.$refs.filterTreeWrapper.style.height = window.innerHeight - 200 + "px";
    // this.loadExpressTemplates();
    // this.loadExpressFeeConditons();
  // },
  methods: {
    loadSupplierList(){
      supplierInfoObj.listAll().then(data=>{
        this.supplierList = data || [];
      });
    },
    handleOnSelectThemeGoods(themeGoods){
      this.addGoodsDialogShowedFlag = false;
      apiGoodsThemeObj.themeAddGoods({id:this.themeId,goodsId:themeGoods.map(el=>el.id)}).then(()=>{
        this.getList();
        this.success();
      });
    },
    handleSelectGoods(row){
      this.$emit('onSelectGoods',row);
    },
    handleSelectSelectedGoods(){
      if(this.selectedThemeGoods.length == 0) {
        this.$message.error('请选择至少一个商品');
        return;
      }
      this.list.forEach(el=>{
        el.selected = false;
      });
      this.$emit('onSelectThemeGoods',this.selectedThemeGoods);
      this.selectedThemeGoods = [];
    },
    handleSelectThemeGoods(row){
      if(row.selected){
        row.selected = false;
        const idx = this.selectedThemeGoods.findIndex(el=>el.id==row.id);
        if(idx > -1) {
          this.selectedThemeGoods.splice(idx,1);
        }
        return;
      }
      row.selected = true;
      if(!this.selectedThemeGoods.some(el=>el.id==row.id)){
        this.selectedThemeGoods.push(row);
      }
    },
    handleShowAddGoodsDialog(){
      this.addGoodsDialogShowedFlag = true;
    },
    handleBatchRemoveGoods(){
        if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.confirm("确定移出所选商品吗").then(() => {
        apiGoodsThemeObj.themeDeleteGoods({ id: this.themeId, goodsId: this.multipleSelection.map(el=>el.id) }).then(() => {
          this.success();
          this.getList();
        });
      });
    },
    handleBatchSetPublishShow(showFlag){
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.confirm(showFlag?"确定设置所选商品主商品可见吗":'确定设置所选商品主商城不可见吗').then(() => {
        apiGoodsObj.modifyPublicShow({ id: this.multipleSelection.map(el=>el.id), showFlag }).then(() => {
          this.success();
          this.getList();
        });
      });
    },
    handleSetPublishShow(row,showFlag){
      this.confirm(showFlag?"确定设置该商品主商城可见吗":'确定设置该商品主商城不可见吗').then(() => {
        apiGoodsObj.modifyPublicShow({ id: [row.id], showFlag }).then(() => {
          this.success();
          this.getList();
        });
      });
    },
    handleRemoveRow(row){
      this.confirm("确定移出该商品吗").then(() => {
        apiGoodsThemeObj.themeDeleteGoods({ id: this.themeId, goodsId: row.id }).then(() => {
          this.success();
          this.getList();
        });
      });
    },
    handleResolve(row) {
      this.$prompt('确认审核通过吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiGoodsObj.checkRealAuth({
              id:row.id,
              checkStatus:10,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.getList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleReject(row) {
      this.$prompt('确认审核拒绝吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiGoodsObj.checkRealAuth({
              id:row.id,
              checkStatus:5,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.getList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    loadReturnAddressList(){
      returnAddressApi.list().then(data=>{
        this.returnAddressList = data || [];
      });
    },
    handleRemoveThemeGoods(idx,item){
      item.selected = false;
      this.selectedThemeGoods.splice(idx,1);
    },
    handleBatchOffline() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.confirm("确认下线选择的分类吗").then(() => {
        this.$service.goods
          .setStatus({ id: this.multipleSelection.map(el => el.id), status: 0 })
          .then(() => {
            this.getList();
            this.success();
          });
      });
    },
    handleBatchResolve(){
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.$prompt('确认审核通过所选商品吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiGoodsObj.checkRealAuth({
              id:this.multipleSelection.map(el=>el.id).join(','),
              checkStatus:10,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.getList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleBatchReject(){
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.$prompt('确认审核拒绝所选商品吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiGoodsObj.checkRealAuth({
              id:this.multipleSelection.map(el=>el.id).join(','),
              checkStatus:5,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.getList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleBatchOnline() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.confirm("确认上线选择的商品吗").then(() => {
        this.$service.goods
          .setStatus({ id: this.multipleSelection.map(el => el.id), status: 1 })
          .then(() => {
            this.getList();
            this.success();
          });
      });
    },
    loadExpressFeeConditons() {
      this.$service.express.queryExpressFreeConditions().then(data => {
        this.expressFreeConditions = data;
      });
    },
    loadExpressTemplates() {
      this.$service.expressTemplate.list().then(data => {
        this.expressTemplates = data;
      });
    },
    handleSetOnline(row) {
      this.confirm("确认上线该商品吗").then(() => {
        this.$service.goods.setStatus({ id: [row.id], status: 1 }).then(() => {
          this.success();
          row.status = 1;
        });
      });
    },
    handleSetOffline(row) {
      this.confirm("确认下线该商品吗").then(() => {
        this.$service.goods.setStatus({ id: [row.id], status: 0 }).then(() => {
          this.success();
          row.status = 0;
        });
      });
    },
    loadAllNodes() {
      this.listCatetory = true;
      apiCategoryObj
        .list()
        .then(data => {
          this.listCatetory = false;
          this.categoryOptions = data;
          this.data2 = [
            {
              id: 0,
              title: "ROOT",
              children: this.categoryOptions
            }
          ];
        })
        .catch(() => {
          this.listCatetory = false;
        });
    },
    onClickNode(data) {
      this.currentSelectedNode = data;
      this.getList();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    deleteRow(row) {
      this.confirm("确认删除该商品吗").then(_ => {
        this.$service.goods.deleteByIds(row.id).then(_ => {
          this.success();
          this.getList();
        });
      });
    },
    addRow() {
      this.dialogFormVisible = true;
      this.isEditing = false;
      Object.keys(this.temp).forEach(key => {
        if(Array.isArray(this.temp[key])){
          this.temp[key] = [];
          return;
        }
        this.temp[key] = '';
      });
      console.log(this.temp);
    },
    editRow(row) {
      this.dialogFormVisible = true;
      this.isEditing = true;
      this.isLoadingDetail = true;
      apiGoodsObj.detail(row.id).then(row=>{
        this.temp = Object.assign({}, row);
        this.temp.goodsImg = this.temp.goodsImg ? this.temp.goodsImg.split(',').filter(el=>el) : [];
        this.temp.goodsDescImg = this.temp.goodsDescImg ? this.temp.goodsDescImg.split(',').filter(el=>el) : [];
      }).finally(()=>{
         this.isLoadingDetail = false;
      });
      // this.temp.category_path = this.temp.category_path ? this.temp.category_path.replace(/,$/ig,'').split(',').map(el=>parseInt(el)):[];
      // if (this.temp.brand_id === 0) {
        // this.temp.brand_id = "";
      // }
      // if (this.temp.express_template_id === 0) {
        // this.temp.express_template_id = "";
      // }
      // if (this.temp.express_free_condition === 0) {
        // this.temp.express_free_condition = "";
      // }
    },
    handleCurrentChange(page) {
      this.listQuery.pageNo = page;
      this.getList();
    },
    handleSizeChange(size) {
      this.listQuery.pageSize = size;
      this.getList();
    },
    getList() {
      let func;
      if(this.selectable) {
        func = apiGoodsSelectedObj.listExclude;  
      }else if(this.themeId === 100){
        this.addGoodsDialogShowedFlag = true;
        func = apiGoodsThemeObj.recommendNorelation
        this.listQuery.recomType = this.recomType

      } else if(this.themeId > 0) {
        if(this.notRelation){
          func = apiGoodsThemeObj.themeNoGoodsList;
          this.listQuery.id = this.themeId;
          this.listQuery.title = this.listQuery.title;
        } else {
          func = apiGoodsThemeObj.themeGoodsList;
          this.listQuery.id = this.themeId;
        }
        
      } else {
        func = apiGoodsObj.list;  
      }
      this.listLoading = true;
      console.log(this.listQuery)
      func(this.listQuery)
        .then(response => {
          const list = response.dataList || [];
          list.forEach(el=>{
            el.selected = false;
          });
          this.list = list;
          console.log(response)
          this.total = response.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    submitFormAction() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.$refs["goodsRule"].valid()) {
            let {skuList,goodsProps} = this.$refs["goodsRule"].getData();
            this.isSubmiting = true;
            let func;
            if (this.isEditing) {
              func = apiGoodsObj.update;
            } else {
              func = apiGoodsObj.create;
            }
            // if(skuList.length == 1){
            //   skuList[0].cover = skuList[0].cover || this.temp.img_srcs[0];
            // }
            let salePrice = 0;
            if(skuList && skuList.length) {
              if(skuList.length == 1 && (!skuList[0].skuProps || skuList[0].skuProps=='{}')) { // 长度是1
                skuList[0].skuImg = this.temp.goodsImg[0];              
              }
              salePrice = skuList.map(el=>el.salePrice).sort((a,b)=>a-b)[0];
            }
            skuList = this.parseArr2Params('skuList',skuList);
            this.temp.returnAddressId='0'
            this.temp.expressTemplateId='0'
            const postData = { ...this.temp, ...skuList,goodsProps,salePrice };
            delete postData.skuList;
            if(!postData.supplierId) {
              delete postData.supplierId;
            }
            func(postData)
              .then(() => {
                this.success();
                this.dialogFormVisible = false;
                this.getList();
              })
              .finally(() => {
                this.isSubmiting = false;
              });
          }
        } else {
          // 显示错误
          this.$refs["goodsRule"].valid();
        }
      });
    }
  }
};
</script>

<style scoped>
.filter-tree-wrapper {
  overflow: auto;
  margin-top: 30px;
}
.title{
  font-size: 18px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}
.selected-theme-goods{
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
